Page({
    data: {
      params: {
        pageNum: 1,
        pageSize: 9999
      },

      xieyiChoose: true,

      hasOrder: false,
      isShopcar: false,
      name: '',
      userTel: '',
      localid: '',
      province: '',
      city: '',
      county: '',
      detailAddress: '',

      wasTrolleyBook: null,

      //上一个页面带过来的参数
      ids: '',
      name2: '',
      coverPic: '',
      price: '',

      isClick: true,


      bookList: [],


      bookInfoIds: [],

      cutDwonFee: 0,

      shipFee: 0,

      bookFee: 0,
      bookFee2: 0,
      yinggaiFu:0,

      discountFee:0,



      localArr: [],


      options: ''

    },

    addLocation () {
      wx.navigateTo({
        url: '/package/index/pages/addLocation/addLocation',
      })
    },

//获取地址列表
  getLocalList(params, bookIds) {
    console.log(bookIds)
    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/address/list/auth',
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
      "token" : wx.getStorageSync('token'),
        "uid" : wx.getStorageSync('uuid')
      },
      success: (res) => {
        console.log(res)

        if (res.data.code == 200) {
          _this.setData({
            localArr: res.data.data.resultList
          })
          if (res.data.data.resultList.length!=0) {
          _this.setData({
            localid: res.data.data.resultList[0].id,
            name: res.data.data.resultList[0].name,
            userTel: res.data.data.resultList[0].userTel,
            province: res.data.data.resultList[0].province,
            city: res.data.data.resultList[0].city,
            county: res.data.data.resultList[0].county,
            detailAddress: res.data.data.resultList[0].detailAddress

          })
          //拉取新订单信息
          _this.getOrderinfo(res.data.data.resultList[0].id,bookIds)
      }
        }
      }
    })
  },


  //拉取新订单信息
  getOrderinfo (localid,bookIds) {
    wx.showLoading({
      title: '计算中',
    })
    var _this = this
    var params = {
      shippingAddressId: localid,
      bookInfoIds: bookIds
    }

    if (this.data.hasOrder) {
      params.orderId = this.data.options.orderIds
    }
     wx.request({
       url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/order/purchase/pre/order/infos/auth',
       data: params,
       method: 'POST',
       header: {
         "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
       "token" : wx.getStorageSync('token'),
         "uid" : wx.getStorageSync('uuid')
       },
       success: (res) => {
         if (res.data.code == 200) {
           wx.hideLoading()
           _this.setData({
             bookFee2: res.data.data.bookFee,
             shipFee: res.data.data.shipFee,
             cutDwonFee: res.data.data.cutDownFee,
             scoreUsed: res.data.data.sdxScores,
             discountFee: res.data.data.discountFee,
             bookFee: _this.Subtr(res.data.data.bookFee, res.data.data.cutDwonFee),
             yinggaiFu: res.data.data.needToPay == 0 ? 0.01 : res.data.data.needToPay
           })


         }else{
           wx.hideLoading()
           wx.showToast({
             title: res.data.msg,
             icon: 'none',
             duration: 2000
           })

          setTimeout(function () {
            wx.navigateBack()
          },2000)
         }
       }
     })
  },

    pay () {
        // var params = {
        //   cp_code: '2017061501',
        //   cp_tran_no: 'T201804300103',
        //   tran_money: 1,
        //   prod_name: 'test',
        //   notify_url: 'http%3A%2F%2Fygapi.lsmart.wang%2Fcallback',
        //   client_ip: '127.0.0.1',
        //   tran_type: '1000',
        //   return_url: 'http%3A%2F%2Fygapi.lsmart.wang%2Fcallback',
        //   user_id: '1805171311305020',
        //   sign: 'f3fa8e7bc96d1de8268aa3820d78b2d2'
        // }
        // wx.request({
        //   url: 'http://unifiedpay.lsmart.wang/pay/unified/preOrder.shtml',
        //   data: params,
        //   method: 'POST',
        //   success: (res) => {

        //   }
        // })
    },

    //添加修改地址
  addDizhi2 (params) {

    console.log(params)
    this.setData({
      localArr: [{
        localid: params.ids,
        name: params.name,
        userTel: params.userTel,
        province: params.province,
        city: params.city,
        county: params.county,
        detailAddress: params.detailAddress
      }],
      localid: params.ids,
      name: params.name,
      userTel: params.userTel,
      province: params.province,
      city: params.city,
      county: params.county,
      detailAddress: params.detailAddress
    })

    this.getOrderinfo(this.data.localid,this.data.bookInfoIds)

  },


  getOrderstatus (params) {
    
   
    return new Promise((resolve, reject)=>{
      wx.request({
        url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/order/purchase/pre/wasSeveral/auth',
        data: params,
        method: 'POST',
        header: {
          "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
          "token": wx.getStorageSync('token'),
          "uid": wx.getStorageSync('uuid')
        },
        success: (res) => {
          resolve(res)
        }
      })
    })
   
  },

  //微信支付
  goPay () {   

    if (this.data.localid == '') {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
      return
    }

    // wx.navigateToMiniProgram({
    //   appId: 'wx490e0363ff3cc1d6',
    //   path: 'pages/sdx/index',
    //   extraData: {
    //     "orderNo": ,
    //     "payCount": 支付金额 最小分
    //   },
    //   //envVersion: 'develop',
    //   fail(res) {
    //     wx.showToast({
    //       title: res.errMsg,
    //       icon: 'none',
    //     });
    //   },
    //   success(res) {
    //     wx.showToast({
    //       title: 'ok',
    //       icon: 'none',
    //     });
    //   },
    // });

    // return
    var _this = this


    

    
  

    var params = {
      shippingAddressId: this.data.localid,
      bookInfoIds: this.data.bookInfoIds,
      scoreUsed: this.data.cutDwonFee,
      shipFee: this.data.shipFee,
      bookFee: this.data.yinggaiFu,
      formerPrice: this.data.bookFee2,
      openId: wx.getStorageSync('openid')
    }
    if (this.data.hasOrder) {
      params.orderNo = this.data.options.orderId
    }


    
    if (!this.data.hasOrder) {
    this.getOrderstatus(params).then((res)=>{
      if (res.data.code == 200) {
        
        if (res.data.data==true) {
          wx.showModal({
        title: '订单',
        content: '订单已经生成,是否去订单列表进行支付',
        cancelText: '否',
        confirmText: '是',
        success: function (res) {
          if (res.cancel) {

            wx.navigateBack()
            return
            //点击取消,默认隐藏弹框
          } else {
            wx.redirectTo({
              url: '/package/my/pages/myOrder/myOrder',
            })

      
          }
        }
      })

        

        }else{
          _this.Paysmoney(params)
        }
      }else{
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })

        return
      }
    })

  }else{
      _this.Paysmoney(params)
  }

    
    //  return
  
  },

  Paysmoney (params) {

    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/order/purchase/pre/order/auth',
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          _this.setData({
            isClick: false
          })
          _this.wxPay(res.data.data)
          if (_this.data.isShopcar == true) {
            var pages = getCurrentPages(); // 当前页面
            var beforePage = pages[pages.length - 2];
            beforePage.payOrder()
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


  getMobansend () {
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/message/sendGoods/auth',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res)=> {
        console.log(res)
      }
    })
  },


  goNopay () {
    return false
  },

  getStatusopen() {

    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/message/findWasNotice/auth',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {

          if (res.data.data == 0) {
            _this.getMessage()
          }else{
            setTimeout(function(){
              _this.setData({
                isClick: true
              })
              wx.navigateBack()
            },2000)
          }
          // _this.setData({
          //   openNew: res.data.data == 0 ? true : false
          // })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


  getDingyue(wasNotice) {

    var _this = this

    var params = {
      wasNotice: wasNotice
    }
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/message/updateWasNotice/auth',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.showToast({
            title: wasNotice == 0 ? '取消授权' : '授权成功',
            icon: 'none'
          })
         
          setTimeout(function (){
            _this.setData({
              isClick: true
            })
            wx.navigateBack()
          },2000)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


  



  getMessage () {
    var _this = this
    wx.requestSubscribeMessage({
      tmplIds: ["vcHLrrKKBZNI2hCHrhEEqo6hOBq6gcZ5lS9nMwG8uMc", "gg3x6wtwo3OiPR0due-tLevMZMONJtltVzEWUCKwvzk"],
      success: (res) => {

        if (res['vcHLrrKKBZNI2hCHrhEEqo6hOBq6gcZ5lS9nMwG8uMc'] === 'accept') {
          
          _this.getDingyue(1)
         
        } else {
          _this.getDingyue(0)
          
        }

      },
      fail(err) {
        //失败
        console.error(err);
        // reject()
      }
    })
  },


  wxPay (data) {
    console.log(data.timeStamp)

    var _this = this


    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.sign,
      success: function (event) {

        console.log('1111111')
        wx.showToast({
          title: '支付成功',
          icon: 'none',
          duration: 2000
        })
        if (_this.data.hasOrder) {

          _this.getStatusopen()
      
          // wx.navigateBack()
        }else{
          if (_this.data.fromType == 3) {
            var pages = getCurrentPages();//获取页面栈
            var beforePage = pages[pages.length - 3];
            beforePage.changeData3()
          }
          var pages = getCurrentPages();//获取页面栈
          var beforePage = pages[pages.length - 2];
          beforePage.changeData()
        
          _this.getStatusopen()
      

        }
      },
      fail: function (error) {
        console.log("99999999999")
        wx.showToast({
          title: '取消支付',
          icon: 'none'
        })

        if (_this.data.hasOrder) {
          wx.navigateBack()
        } else {
          if (_this.data.fromType == 3) {
            var pages = getCurrentPages();//获取页面栈
            var beforePage = pages[pages.length - 3];
            beforePage.changeData3()
          }
          var pages = getCurrentPages();//获取页面栈
          var beforePage = pages[pages.length - 2];
          beforePage.changeData()


          // _this.getStatusopen()
          
          setTimeout(function () {
            _this.setData({
              isClick: true
            })
            if (!_this.data.hasOrder) {
              wx.redirectTo({
                url: '/package/my/pages/myOrder/myOrder',
              })
            }else{
              wx.navigateBack()
            }
            
          },2000)

        }
      },
      complete: function (e) {
        // if (e.errMsg == 'requestPayment:ok') {
        //   console.log('222222222')
        //   wx.showToast({
        //     title: '支付成功',
        //     icon: 'none'
        //   })

        //   if (_this.data.hasOrder) {
        //     wx.navigateBack()
        //   } else {
        //     var pages = getCurrentPages();//获取页面栈
        //     var beforePage = pages[pages.length - 2];
        //     beforePage.changeData()

        //     setTimeout(function () {
        //       wx.navigateBack()
        //     }, 2000)
        //   }
        // }

      }
    })

    return
    wx.navigateToMiniProgram({
      appId: 'wxdd8c93c8a6b5df1c',
      path: 'pages/sdx/index',
      extraData: {
        "orderNo": data.orderNo,
        "payCount": 0.01
        // "payCount": _this.data.yinggaiFu
      },
      //envVersion: 'develop',
      fail(res) {
        wx.showToast({
          title: res.errMsg,
          icon: 'none',
        });
      },
      success(res) {
        wx.showToast({
          title: 'ok',
          icon: 'none',
        });
      },
    });

    // return
  },

    onLoad (options) {


      console.log(options.bookIdstr)

      console.log(options.bookArr.length)

      // var bookInfoIds = thi

      this.setData({
        options: options
      })

      if (options.fromType) {
        this.setData({
          fromType: options.fromType
        })
      }

      var arr = []
      this.setData({
        isShopcar: this.data.options.shopCar ? true: false,
        hasOrder: this.data.options.orderId ? true : false,
        bookList: JSON.parse(decodeURIComponent(options.bookArr)),
        bookInfoIds: options.bookIdstr
      })

      this.data.bookList.forEach(function (item, index) {
        arr.push(item.bookId)
        // arr.push(item.bookId)
      })

      // this.setData({
      //   bookInfoIds: arr.length == 0 ? arr[0] : arr.join(',')
      // })
      this.getLocalList(this.data.params, this.data.bookInfoIds)
    },

    onShow () {
      // console.log(JSON.parse(options.bookArr))
    },




// 假发
  accAdd(arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
     try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
     m = Math.pow(10, Math.max(r1, r2))
     return (arg1 * m + arg2 * m) / m
   },

  // 剑法
  Subtr(arg1, arg2) {
    var r1, r2, m, n;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2));
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
   },


  //协议选择
  chooseXieyi () {
    var chooseType = this.data.xieyiChoose

    this.setData({
      xieyiChoose: !chooseType
    })
  },

  //用户协议
  agreeXiexi () {
    wx.navigateTo({
      url: '/package/index/pages/agreeXiexi/agreeXiexi'
    })
  }
})
